// app/controller/users.js
const Controller = require('../controller/baseController')
const { Op } = require('sequelize')

class UserController extends Controller {
	// 获取所有的列表不分页 用于打印生成excel表格
	async listAll() {
		const { ctx } = this
		let options = {
			distinct: true,
			include: [
				{
					through: { attributes: [] },
					model: this.ctx.model.Role,
					attributes: ['id', 'name', 'remark'],
				},
			],
		}
		const data = await ctx.service.user.listAll(options)
		console.log(data)
		ctx.helper.success({ data })
	}
	async list() {
		const { ctx } = this
		const {
			query: { pageSize = 8, currentPage = 1 },
			helper,
		} = ctx
		let options = {
			limit: helper.toInt(pageSize),
			offset: (helper.toInt(currentPage) - 1) * helper.toInt(pageSize),
			distinct: true,
			include: [
				{
					through: { attributes: [] },
					model: this.ctx.model.Role,
					attributes: ['id', 'name', 'remark'],
					where: {
						status: true,
					},
				},
			],
		}

		const data = await ctx.service.user.list(options)
		ctx.helper.success({ data })
	}
	async findLike() {
		const { ctx } = this
		const {
			query: {
				username,
				begin,
				end,
				status,
				phone,
				role,
				pageSize = 8,
				currentPage = 1,
			},
			helper,
		} = ctx
		let where = {}
		if (status) {
			where['status'] = {
				[Op.eq]: ctx.query.status ? JSON.parse(ctx.query.status) : true,
			}
		}
		if (begin && end) {
			where['createdAt'] = {
				[Op.between]: [ctx.query.begin, ctx.query.end],
			}
		}
		let relative = {}
		if (role) {
			relative['remark'] = {
				[Op.eq]: role,
			}
		}
		let options = {
			limit: helper.toInt(pageSize),
			offset: (helper.toInt(currentPage) - 1) * helper.toInt(pageSize),
			distinct: true,
			where: {
				username: {
					[Op.substring]: username,
				},
				phone: {
					[Op.substring]: phone,
				},
				...where,
			},

			include: [
				{
					through: { attributes: [] },
					model: this.ctx.model.Role,
					attributes: ['id', 'name', 'remark'],
					where: {
						status: {
							[Op.eq]: true,
						},
						...relative,
					},
				},
			],
		}
		console.log(username)
		const data = await ctx.service.user.findLike(options)
		helper.success({ data })
	}
	async add() {
		const { ctx } = this
		const {
			request: {
				body: { username, password },
			},
			service: { user },
			helper,
		} = ctx

		const res = await user.add(ctx.request.body)
		// 删除对象的password 属性
		if (res.flag) {
			if (res.dataValues) delete res.dataValues.password
			helper.success({
				data: res.dataValues,
				msg: '创建用户成功',
				code: 200,
			})
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	async update() {
		const { ctx } = this
		let {
			request: { body },
			service: { user },
			helper,
		} = ctx
		if (!body.id) return helper.fail({ msg: 'id关键字缺失！' })

		const res = await user.update(body)
		if (res.flag) {
			helper.success({ msg: '用户修改成功！' })
		} else {
			helper.fail({ msg: '用户修改失败！' })
		}
	}
	async updatePwd() {
		const { ctx } = this
		let {
			request: { body },
			helper,
		} = ctx
		if (!body.id) return helper.fail({ msg: 'id关键字缺失！' })
		const res = await ctx.service.user.updatePwd(body)
		if (res) {
			helper.success({ msg: '密码修改成功！' })
		} else {
			helper.fail({ msg: '密码修改改失败！' })
		}
	}
	async updateList() {
		const { ctx } = this
		const res = await ctx.service.user.updateList(ctx.request.body.users)
		if (res.flag && res.count) {
			ctx.helper.success({
				msg: '批量添加成功！',
				inserCount: res.count,
			})
		} else {
			ctx.helper.fail({ msg: '批量添加失败！数据重复！' })
		}
	}
	async del() {
		const { ctx } = this
		const {
			request: {
				body: { ids },
			},
			service: { user },
			helper,
		} = ctx
		if (!ids) return helper.fail({ msg: '缺失关键参数！', code: 400 })
		const res = await user.del(ids)

		if (res.flag) {
			helper.success({ msg: '删除成功！' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	async login() {
		const { ctx } = this
		const {
			request: {
				body: { username, password, captcha },
			},
			service: { user },
			helper,
		} = ctx

		if (!username || !username.trim()) {
			return helper.fail({ msg: '用户名不能为空！' })
		}
		if (!password || !password.trim()) {
			return helper.fail({ msg: '密码不能为空！' })
		}
		if (!captcha || !captcha.trim()) {
			return helper.fail({ msg: '验证码不能为空！' })
		}
		const { flag, msg } = helper.checkCaptche(captcha)
		if (!flag) return helper.fail({ msg })
		const res = await user.login(ctx.request.body)
		if (res.flag) {
			helper.success({ msg: res.msg, data: res.data })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	async register() {
		const { ctx } = this
		const {
			request: {
				body: { username, password },
			},
			service: { user },
			helper,
		} = ctx

		const res = await user.add(ctx.request.body)
		if (res.flag) {
			helper.success({ data: res.data.dataValues, msg: '添加成功' })
		} else {
			helper.fail({ msg: res.msg })
		}
	}
	async loginOut() {
		const { ctx } = this
		ctx.cookies.set('token', '', {
			maxAge: 0,
		})
		ctx.helper.success({ msg: '退出登录！' })
	}
	async captche() {
		this.ctx.helper.captche()
	}
	async getUserInfo() {
		const { ctx } = this
		const { id } = ctx.session.userInfo
		if (id) {
			// 刪除密码属性
			const { dataValues } = await ctx.model.User.findOne({
				attributes: { exclude: ['password'] },
				where: {
					id,
				},
				distinct: true,
				include: [
					{
						through: { attributes: [] },
						model: this.ctx.model.Role,
						attributes: ['name', 'remark'],
					},
				],
			})

			ctx.helper.success({ data: dataValues })
		} else {
			ctx.helper.fail({ msg: '未携带 Authorization ' })
		}
	}
	async getRemarks() {
		const { ctx } = this
		// 当前登录用户的id
		const { id } = ctx.session.userInfo
		// 获取权限编码
		let remarks = []
		await this.app.model
			.query(
				`
				SELECT DISTINCT
				prim 
				FROM
				role_user ur
				LEFT JOIN role_menu rm ON ur.role_id = rm.rid 
				WHERE
				ur.user_id = ?;
				`,
				{ replacements: [id], type: 'SELECT' }
			)
			.then((res) => {
				remarks = res.map((item) => String(item.prim))
				// 把当前用户的 权限码存储到session中
			})
		ctx.helper.success({ data: remarks })
	}
	async getUserInfoById() {
		const { ctx } = this

		const { id } = ctx.params
		console.log(id)
		const res = await ctx.service.user.getUserInfoById(id)

		if (res) {
			ctx.helper.success({ data: res })
		}
	}
}

module.exports = UserController
